<?php

namespace app\api\controller;

use app\api\model\OrderCommon;
use app\api\model\ConfigAlipay;
use app\api\model\Topup;
use think\Db;
use think\Request;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;

class Alipay extends Common
{
    protected $config;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $config = ConfigAlipay::get(['types' => 1, 'is_select' => 1]);

        $this->config = [
            'alipay' => [
                'app_id' => $config['appid'],
                'notify_url' => url('api/Alipay/notify', '', '', true),
                'ali_public_key' => $config['public_key'],
                'private_key' => $config['private_key'],
            ],
        ];
    }

    public function tradeAppPay($order_sn, $subject = '账户充值', $returnJson = true, $uid = 0)
    {
        $result = $this->check($order_sn);
    
        if ($result['code'] != 200) {
            return $this->miss($result['msg']);
        }
    
        $total_amount = $result['data']['total_amount'];
        
        $config_biz = [
            'out_trade_no' => $order_sn,
            'total_amount' => sprintf("%.2f", $total_amount),
            'subject' => $subject,
        ];

        if ($uid) {
            $config_biz['passback_params'] = http_build_query(['uid'=>$uid]);
        }

        $pay = new Pay($this->config);

        $result = $pay->driver('alipay')->gateway('app')->pay($config_biz);

        return $returnJson ? $this->pass(['url' => $result]) : $result;
    }
    
    private function check($out_trade_no)
    {
        $state = 0;
        
        $data = (new Topup)->master()->where(['numbers' => $out_trade_no, 'state' => 0])->find();
        
        if ($data) {
            $state = 1;
            $money = $data['price'];
        }
        
        if (!$state) {
            $data = (new OrderCommon)->master()->where(['number' => $out_trade_no, 'status' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['money'];
            }
        }
        if (!$state) {
            $data = Db::name('mall_order')->master()->where(['number' => $out_trade_no, 'status' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['money'];
            }
        }
        
        if (!$state) {
            $data = Db::name('order_of_service')->master()->where(['number' => $out_trade_no, 'paystate' => 0, 'state' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }
        
        if (!$state) {
            $data = Db::name('user_flag')->master()->where(['number' => $out_trade_no, 'paystate' => 0, 'status' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }

        if (!$state) {
            $data = Db::name('user_address_red_packet')->master()->where(['number' => $out_trade_no, 'type' => 1, 'paystate' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['totalprice'];
            }
        }

        if (!$state) {
            $data = Db::name('order_of_addressgood')->master()->where(['number' => $out_trade_no, 'status' => 0, 'paystate' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }

        if (!$state) {
            $data = Db::name('activity_join')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->find();
            
            if ($data) {
                $state = 1;
                $money = $data['price'];
            }
        }
        
        if (!$state) {
            return ['code' => 400, 'msg' => '订单不存在'];
        } else {
            return ['code' => 200, 'data' => ['total_amount' => $money]];
        }
    }

    public function notify(Request $request)
    {
        $pay = new Pay($this->config);
        $verify = $pay->driver('alipay')->gateway('app')->verify($_POST);

        if ($verify) {
            $passback_params = [];
            if (isset($verify['passback_params'])) {
                parse_str($verify['passback_params'], $passback_params);
            }
            $verify['other_data'] = $passback_params;
            if (in_array($verify['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                OrderCommon::notify($verify['out_trade_no'], $verify);
            } else {
                exit('fail');
            }
        } else {
            exit('fail');
        }
        exit('success');
    }


    public function checkOrder($out_trade_no)
    {
        $pay = new Pay($this->config);
        $result = $pay->driver('alipay')->gateway('app')->find($out_trade_no);

        if ($result['trade_status'] == 'TRADE_SUCCESS'){
            $result['time_end_timestamp'] = strtotime($result['send_pay_date']);
            return $result;
        }
        return false;
    }
}